package com.stock_t.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stock_t.dto.ApiResponse;
import com.stock_t.dto.HistoricalPositionDTO;
import com.stock_t.dto.HistoricalPositionPageDTO;
import com.stock_t.dto.StockStatisticsResponse;
import com.stock_t.entity.HistoricalPosition;
import com.stock_t.mapper.HistoricalPositionMapper;
import com.stock_t.service.HistoricalPositionService;
import com.stock_t.service.StockStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HistoricalPositionServiceImpl implements HistoricalPositionService {

    @Autowired
    private HistoricalPositionMapper historicalPositionMapper;

    @Autowired
    private StockStatisticsService stockStatisticsService;

    @Override
    public ApiResponse<HistoricalPositionPageDTO> getHistoricalPositionPage(int current, int size, String stockCode, String sortType, String sortOrder) {
        try {
            Page<HistoricalPosition> page = new Page<>(current, size);
            QueryWrapper<HistoricalPosition> queryWrapper = new QueryWrapper<>();
            
            // 根据股票代码筛选
            if (stockCode != null && !stockCode.trim().isEmpty()) {
                queryWrapper.eq("stock_code", stockCode.trim());
            }
            
            // 动态排序处理
            String sortColumn = getSortColumn(sortType);
            boolean isAsc = "asc".equalsIgnoreCase(sortOrder);
            
            if (isAsc) {
                queryWrapper.orderByAsc(sortColumn);
            } else {
                queryWrapper.orderByDesc(sortColumn);
            }
            
            IPage<HistoricalPosition> resultPage = historicalPositionMapper.selectPage(page, queryWrapper);
            
            HistoricalPositionPageDTO pageDTO = new HistoricalPositionPageDTO();
            pageDTO.setTotal(resultPage.getTotal());
            pageDTO.setSize(resultPage.getSize());
            pageDTO.setCurrent(resultPage.getCurrent());
            pageDTO.setPages(resultPage.getPages());
            
            List<HistoricalPositionDTO> records = resultPage.getRecords().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
            
            pageDTO.setRecords(records);
            
            return ApiResponse.success(pageDTO);
        } catch (Exception e) {
            log.error("查询历史持仓记录失败", e);
            return ApiResponse.error(500, "查询历史持仓记录失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse<String> uploadHistoricalPosition(MultipartFile file, Date positionDate, String stockCode, String stockName) {
        try {
            if (file == null || file.isEmpty()) {
                return ApiResponse.error(400, "上传文件不能为空");
            }
            
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
            }
            
            if (!fileExtension.matches("jpg|jpeg|png|gif")) {
                return ApiResponse.error(400, "只支持jpg、jpeg、png、gif格式的图片");
            }
            
            // 获取股票统计信息
            StockStatisticsResponse.LatestData latestData = stockStatisticsService.getLatestData(stockCode);
            
            HistoricalPosition position = new HistoricalPosition();
            position.setPositionDate(positionDate);
            position.setStockCode(stockCode);
            position.setStockName(stockName);
            position.setPositionImage(file.getBytes());
            position.setImageFormat(fileExtension);
            position.setImageSize((int) file.getSize());
            
            // 从股票统计服务获取实时数据
            if (latestData != null) {
                position.setTotalValue(latestData.getMarketValue() != null ? latestData.getMarketValue() : BigDecimal.ZERO);
                position.setTotalProfit(latestData.getProfitLoss() != null ? latestData.getProfitLoss() : BigDecimal.ZERO);
                position.setPositionCount(latestData.getTotalShares() != null ? latestData.getTotalShares() : 0);
            } else {
                position.setTotalValue(BigDecimal.ZERO);
                position.setTotalProfit(BigDecimal.ZERO);
                position.setPositionCount(0);
            }
            
            position.setCreatedTime(new Date());
            position.setUpdatedTime(new Date());
            
            historicalPositionMapper.insert(position);
            
            return ApiResponse.success("历史持仓图片上传成功");
        } catch (IOException e) {
            log.error("上传历史持仓图片失败", e);
            return ApiResponse.error(500, "上传历史持仓图片失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse<String> deleteHistoricalPosition(Long id) {
        try {
            int result = historicalPositionMapper.deleteById(id);
            if (result > 0) {
                return ApiResponse.success("删除历史持仓记录成功");
            } else {
                return ApiResponse.error(404, "未找到对应的历史持仓记录");
            }
        } catch (Exception e) {
            log.error("删除历史持仓记录失败", e);
            return ApiResponse.error(500, "删除历史持仓记录失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse<String> batchDeleteHistoricalPosition(List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return ApiResponse.error(400, "请选择要删除的记录");
            }
            
            int result = historicalPositionMapper.deleteBatchIds(ids);
            return ApiResponse.success("批量删除成功，共删除" + result + "条记录");
        } catch (Exception e) {
            log.error("批量删除历史持仓记录失败", e);
            return ApiResponse.error(500, "批量删除历史持仓记录失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse<HistoricalPositionDTO> getHistoricalPositionById(Long id) {
        try {
            HistoricalPosition position = historicalPositionMapper.selectById(id);
            if (position == null) {
                return ApiResponse.error(404, "未找到对应的历史持仓记录");
            }
            
            HistoricalPositionDTO dto = convertToDTO(position);
            return ApiResponse.success(dto);
        } catch (Exception e) {
            log.error("查询历史持仓记录失败", e);
            return ApiResponse.error(500, "查询历史持仓记录失败: " + e.getMessage());
        }
    }

    private HistoricalPositionDTO convertToDTO(HistoricalPosition entity) {
        HistoricalPositionDTO dto = new HistoricalPositionDTO();
        BeanUtils.copyProperties(entity, dto);
        
        if (entity.getPositionImage() != null) {
            String base64Image = Base64.getEncoder().encodeToString(entity.getPositionImage());
            dto.setImageBase64("data:image/" + entity.getImageFormat() + ";base64," + base64Image);
        }
        
        return dto;
    }
    
    /**
     * 将前端排序类型映射到数据库字段名
     */
    private String getSortColumn(String sortType) {
        switch (sortType) {
            case "date":
                return "position_date";
            case "createdTime":
                return "created_time";
            case "totalValue":
                return "total_value";
            case "totalCount":
                return "position_count";
            default:
                return "position_date"; // 默认按日期排序
        }
    }
}